package org.zizi.util;

import java.io.IOException;
import java.io.Writer;


/** 分页器 */
public class Pagging
{
	public static final int DEFAULT_LIMIT = 15;
	
	private int limit;	//每页显示多少
	private int total;
	private int page;	//从1开始
	
	public Pagging(int page)
	{
		this(DEFAULT_LIMIT, page);
	}
	
	public Pagging(int limit, int page)
	{
		if (limit <= 0) throw new IllegalArgumentException("limit must be positive.");
		this.limit = limit;
		this.page = page;
	}
	
	public void setTotal(int total)
	{
		this.total = total;
	}
	
	public int getLimit()
	{
		return limit;
	}
	
	public int getOffset()
	{
		return (page - 1) * limit;
	}
	
	public int getPages()	//共有多少页
	{
		return (total - 1) / limit + 1;
	}
	
	/**
	 * 画出
	 * @param capacity 要显示的数量
	 * @throws IOException 
	 */
	public void draw(int capacity, Writer writer, String string, String current) throws IOException
	{
		int c = page;
		int a = (capacity - 1) / 2;
		
		c = c - a;
		if (c < 1) c = 1;
		if (c + capacity - 1 > getPages()) c = getPages() - capacity + 1;
		if (c < 1) c = 1;
		
		//first
		String first = string.replace("@PAGE", "1").replace("@TEXT", "<<");
		writer.write(first);
		
		//pre
		String previous = string.replace("@PAGE", String.valueOf(page <= 1 ? 1 : (page - 1))).replace("@TEXT", "<");
		writer.write(previous);
		
		for (int i = 0; i < capacity; i++)
		{
			if (c + i > getPages()) break;
			
			if (c + i == page)
			{
				String out = current.replace("@PAGE", String.valueOf(c + i)).replace("@TEXT", String.valueOf(c + i));
				writer.write(out);
			}
			else
			{
				String out = string.replace("@PAGE", String.valueOf(c + i)).replace("@TEXT", String.valueOf(c + i));
				writer.write(out);
			}
		}
		
		//next
		String next = string.replace("@PAGE", String.valueOf(page >= getPages() ? page : (page + 1))).replace("@TEXT", ">");
		writer.write(next);
		
		//last
		String last = string.replace("@PAGE", String.valueOf(getPages())).replace("@TEXT", ">>");
		writer.write(last);
	}
}
